const { SuccessModel, ErrorModel } = require('../model/resModel')
const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog')

const handleBlogRouter = (req, res) => {
  const id = req.query.id
  // 获取博客列表
  if (req.method === 'GET' && req.path === '/api/blog/list') {
    const author = req.query.author || ''
    const keyword = req.query.keyword || ''
    console.log('query', req.query, keyword)

    return getList(author, keyword).then(data => {
      if(data) {
        return new SuccessModel(data)
      } else {
        return new ErrorModel('未查到数据')
      }
    })
  }

  // 获取博客详情
  if (req.method === 'GET' && req.path === '/api/blog/detail') {
    return getDetail(id).then(data => {
      if(data) {
        return new SuccessModel(data)
      } else {
        return new ErrorModel('未查到数据')
      }
    })
  }

  // 新建一篇博客
  if (req.method === 'POST' && req.path === '/api/blog/new') {
    const params = req.body
    params.author = 'yang'
    return newBlog(params).then(data => {
      if(data) {
        return new SuccessModel(data)
      } else {
        return new ErrorModel('插入失败')
      }
    })
  }

  // 更新一篇博客
  if (req.method === 'POST' && req.path === '/api/blog/update') {
    return updateBlog(id, req.body).then(value => {
      if(value) {
        return new SuccessModel('更新成功')
      } else {
        return new ErrorModel('更新失败')
      }
    })
  }

  // 删除一篇博客
  if (req.method === 'POST' && req.path === '/api/blog/del') {
    const author = 'yang'
    return delBlog(id, author).then(value => {
      if(value) {
        return new SuccessModel('删除成功')
      } else {
        return new ErrorModel('删除失败')
      }
    })
  }
}

module.exports = handleBlogRouter